/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import numeral from "numeral";
import { Icon } from "antd";

class NumberDelay extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      number: this.formatNumber(),
    };
  }

  formatNumber = (number = 0) => {
    const { format = "0,0" } = this.props;
    return numeral(number).format(format);
  };

  clearTimer = () => {
    const { timer } = this;
    timer && clearInterval(timer);
  };

  setNumber = number => {
    this.setState({
      number: this.formatNumber(number),
    });
  };

  startTimer = props => {
    this.clearTimer();
    const { number, delay = 100, speed = 1 } = props;
    const startNumber = 1 * number;
    // 非数字
    if (typeof startNumber !== "number" || Number.isNaN(startNumber)) {
      this.setNumber(0);
      return;
    }
    let current = 0;
    let increment = speed * Math.floor(startNumber / delay) || 1;
    this.timer = setInterval(() => {
      current = increment + current;
      if (current >= startNumber) {
        current = startNumber;
        this.clearTimer();
      }
      this.setNumber(current);
    }, speed);
  };

  componentWillReceiveProps(props) {
    const { number } = props;
    if (number >= 0 && number !== this.props.number) {
      this.startTimer(props);
    }
  }

  componentDidMount() {
    const { number } = this.props;
    if (number <= 0) {
      this.setNumber(number);
    } else {
      this.startTimer(this.props);
    }
  }

  componentWillUnmount() {
    this.clearTimer();
  }

  render() {
    const { loading = false, ...rest } = this.props;
    const { number } = this.state;
    return loading ? <Icon spin type="loading" /> : <span {...rest}>{number}</span>;
  }
}
export { numeral, NumberDelay as default };
